//
//  JDSimpleOrderDetailViewController.swift
//  DragonWallet
//
//  Created by volantPig on 2025/4/6.
//

import UIKit
import SwiftyJSON

class JDSimpleOrderDetailViewController: JDBaseViewController {

    var orderType: JDOrderType = .waitingPay
    var orderId: String?

    var topContainerView: UIView?
    var topLine: UIView?
    var topTitlelabel: UILabel?
    var orderStatusLabel: UILabel?
    var orderStatusImageV: UIImageView?
    var contentLabel: UILabel?
    var bottomLine : UIView?
    var totalPriceLabel: UILabel?
    
    var bottomContainerView: UIView?
    
    var copyButton: UIButton?
    var orderNoView: JDCellInfoCellSubView?
    var orderTimeView: JDCellInfoCellSubView?
    var payTimeView: JDCellInfoCellSubView?
    
    
    var detailModel: JDSimpleOrderDetailModel?
    
    
    var bottomToolBarContainerView: UIView?
    var tipsLabel: UILabel?
    var totalPriceTitle: UILabel?
    var bottomTotalPriceLabel: UILabel?
    var cancelButton: UIButton?
    var continuePaymentButton: UIButton?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.setupConfig()
        self.setupUIElements()
        self.getNetData()
        // Do any additional setup after loading the view.
    }
    
    func setupConfig() {
        self.setupLeftBackItem()
        self.setupNavigationTitle("尨看板详情")
    }
    
    func setupUIElements() {
        self.setupTopContainerView()
        self.setupBottomContainerView()
        
        if self.orderType == .waitingPay {
            self.setupBottomToolView()
        }

    }
    
    func setupBottomToolView() {
        self.bottomToolBarContainerView = UIView()
        self.view.addSubview(self.bottomToolBarContainerView!)
        self.bottomToolBarContainerView?.snp.makeConstraints({ make in
            make.left.right.equalTo(self.view)
            make.bottom.equalTo(self.view)
            make.height.equalTo(76)
        })
        self.bottomToolBarContainerView?.backgroundColor = .white

        self.totalPriceTitle = UILabel()
        self.bottomToolBarContainerView?.addSubview(self.totalPriceTitle!)
        totalPriceTitle?.snp.makeConstraints { make in
            make.left.equalTo(self.bottomToolBarContainerView!).offset(12)
            make.centerY.equalTo(self.bottomToolBarContainerView!)
        }
        totalPriceTitle?.text = "合计:"
        totalPriceTitle?.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 14, weight: .regular), textColor: color("#333333"), numberOfLines: 1)
        totalPriceTitle?.isHidden = true
        
        self.bottomTotalPriceLabel = UILabel()
        self.bottomToolBarContainerView?.addSubview(self.bottomTotalPriceLabel!)
        self.bottomTotalPriceLabel?.snp.makeConstraints({ make in
            make.left.equalTo(self.totalPriceTitle!.snp.right)
            make.bottom.equalTo(self.totalPriceTitle!)
        })
        self.bottomTotalPriceLabel?.text = "￥0.00"
        self.bottomTotalPriceLabel?.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 20, weight: .semibold), textColor: color("#FA6161"))
        self.bottomTotalPriceLabel?.isHidden = true
        
        self.continuePaymentButton = UIButton(type: .custom)
        self.bottomToolBarContainerView?.addSubview(self.continuePaymentButton!)
        self.continuePaymentButton?.snp.makeConstraints({ make in
            make.right.equalTo(self.bottomToolBarContainerView!).offset(-12)
            make.centerY.equalTo(self.bottomToolBarContainerView!).offset(-5)
            make.size.equalTo(CGSize(width: 105, height: 40))
        })
        self.continuePaymentButton?.layer.cornerRadius = 20
        self.continuePaymentButton?.backgroundColor = color("#FA6161")
        self.continuePaymentButton?.setTitle("继续付款", for: .normal)
        self.continuePaymentButton?.setTitleColor(.white, for: .normal)
        self.continuePaymentButton?.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .regular)
        self.continuePaymentButton?.addTarget(self, action: #selector(continuePayAction), for: .touchUpInside)
        
        self.cancelButton = UIButton(type: .custom)
        self.bottomToolBarContainerView?.addSubview(self.cancelButton!)
        self.cancelButton?.snp.makeConstraints({ make in
            make.right.equalTo(self.bottomToolBarContainerView!).offset(-129)
            make.centerY.equalTo(self.bottomToolBarContainerView!).offset(-5)
            make.size.equalTo(CGSize(width: 105, height: 40))
        })
        self.cancelButton?.layer.cornerRadius = 20
        self.cancelButton?.backgroundColor = color("#F5F6F8")
        self.cancelButton?.setTitle("取消订单", for: .normal)
        self.cancelButton?.setTitleColor(color("#8D9198"), for: .normal)
        self.cancelButton?.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .regular)
        self.cancelButton?.addTarget(self, action: #selector(cancelOrderAction(_:)), for: .touchUpInside)
        
        self.tipsLabel = UILabel()
        self.view.addSubview(self.tipsLabel!)
        self.tipsLabel?.snp.makeConstraints({ make in
            make.left.right.equalTo(self.view)
            make.bottom.equalTo(self.bottomToolBarContainerView!.snp.top)
            make.height.equalTo(38)
        })
        self.tipsLabel?.backgroundColor = color("#333333").withAlphaComponent(0.8)
        self.tipsLabel?.text = "5分钟后订单关闭，请尽快完成支付"
        self.tipsLabel?.labelConfig(textAlignment: .center, font: UIFont.systemFont(ofSize: 14, weight: .regular), textColor: .white)
        self.tipsLabel?.isHidden = true
    }
    
    func setupTopContainerView() {
        
        self.topContainerView = UIView()
        self.view.addSubview(self.topContainerView!)
        self.topContainerView?.snp.makeConstraints { make in
            make.top.equalTo(self.view).offset(statusBarHeight+44)
            make.leading.equalTo(self.view).offset(12)
            make.trailing.equalTo(self.view).offset(-12)
        }
        self.topContainerView?.layer.cornerRadius = 8
        self.topContainerView?.backgroundColor = .white
        
        self.topLine = UIView()
        self.topContainerView?.addSubview(self.topLine!)
        self.topLine?.snp.makeConstraints { make in
            make.leading.equalTo(self.topContainerView!).offset(12)
            make.trailing.equalTo(self.topContainerView!).offset(-12)
            make.top.equalTo(self.topContainerView!).offset(52)
            make.height.equalTo(1)
        }
        self.topLine?.backgroundColor = color("#F5F6F8")
        
        self.topTitlelabel = UILabel()
        self.topContainerView?.addSubview(self.topTitlelabel!)
        self.topTitlelabel?.snp.makeConstraints { make in
            make.top.equalTo(self.topContainerView!)
            make.bottom.equalTo(self.topLine!.snp.top)
            make.leading.equalTo(self.topContainerView!).offset(12)
        }
        self.topTitlelabel?.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 16, weight: .semibold), textColor: color("#333333"), numberOfLines: 1)
        
        self.orderStatusLabel = UILabel()
        self.topContainerView?.addSubview(self.orderStatusLabel!)
        self.orderStatusLabel?.snp.makeConstraints { make in
            make.trailing.equalTo(self.topContainerView!).offset(-12)
            make.centerY.equalTo(self.topTitlelabel!)
        }
        self.orderStatusLabel?.labelConfig(textAlignment: .right, font: UIFont.systemFont(ofSize: 14, weight: .regular), textColor: color("#333333"), numberOfLines: 1)
        
        self.orderStatusImageV = UIImageView()
        self.topContainerView?.addSubview(self.orderStatusImageV!)
        self.orderStatusImageV?.snp.makeConstraints { make in
            make.trailing.equalTo(self.orderStatusLabel!.snp.leading).offset(-5)
            make.centerY.equalTo(self.orderStatusLabel!)
            make.size.equalTo(CGSizeMake(16, 16))
        }
        
        self.contentLabel = UILabel()
        self.topContainerView?.addSubview(self.contentLabel!)
        self.contentLabel?.snp.makeConstraints { make in
            make.leading.equalTo(self.topContainerView!).offset(12)
            make.trailing.equalTo(self.topContainerView!).offset(-12)
            make.top.equalTo(self.topLine!.snp.bottom)
            make.height.greaterThanOrEqualTo(53)
        }
        self.contentLabel?.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 16, weight: .regular), textColor: color("#333333"), numberOfLines: 0)
        
        self.bottomLine = UIView()
        self.topContainerView?.addSubview(self.bottomLine!)
        self.bottomLine?.snp.makeConstraints { make in
            make.leading.equalTo(self.topContainerView!).offset(12)
            make.trailing.equalTo(self.topContainerView!).offset(-12)
            make.height.equalTo(1)
            make.top.equalTo(self.contentLabel!.snp.bottom)
            make.bottom.equalTo(self.topContainerView!).offset(-59)
        }
        self.bottomLine?.backgroundColor = color("#F5F6F8")
        
        self.totalPriceLabel = UILabel()
        self.topContainerView?.addSubview(self.totalPriceLabel!)
        self.totalPriceLabel?.snp.makeConstraints { make in
            make.leading.equalTo(self.topContainerView!).offset(12)
            make.top.equalTo(self.bottomLine!.snp.bottom)
            make.bottom.equalTo(self.topContainerView!)
        }
    
    }
    
    func setupBottomContainerView() {
        self.bottomContainerView = UIView()
        self.view.addSubview(self.bottomContainerView!)
        self.bottomContainerView?.snp.makeConstraints { make in
            make.top.equalTo(self.topContainerView!.snp.bottom).offset(10)
            make.leading.trailing.equalTo(self.topContainerView!)
        }
        self.bottomContainerView?.layer.cornerRadius = 8
        self.bottomContainerView?.backgroundColor = .white
        
//        self.copyButton = UIButton(type: .custom)
//        self.bottomContainerView?.addSubview(self.copyButton!)
//        self.copyButton?.snp.makeConstraints { make in
//            make.trailing.equalTo(self.bottomContainerView!).offset(-12)
//            make.top.equalTo(self.bottomContainerView!).offset(9)
//            make.height.equalTo(32)
//        }
//        self.copyButton?.backgroundColor = .red
//        self.copyButton?.setTitle("复制", for: .normal)
//        self.copyButton?.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .regular)
//        self.copyButton?.setTitleColor(color("#FA6161"), for: .normal)
        
        
        self.orderNoView = JDCellInfoCellSubView()
        self.bottomContainerView?.addSubview(self.orderNoView!)
        self.orderNoView?.snp.makeConstraints { make in
            make.leading.equalTo(self.bottomContainerView!)
//            make.trailing.equalTo(self.copyButton!.snp.leading)
            make.trailing.equalTo(self.bottomContainerView!)
            make.top.equalTo(self.bottomContainerView!).offset(9)
            make.height.equalTo(32)
        }
        self.orderNoView?.titleLabel?.text = "订单编号"
        
        self.orderTimeView = JDCellInfoCellSubView()
        self.bottomContainerView?.addSubview(self.orderTimeView!)
        self.orderTimeView?.snp.makeConstraints { make in
            make.top.equalTo(self.orderNoView!.snp.bottom)
            make.height.equalTo(32)
            make.leading.equalTo(self.bottomContainerView!)
            make.trailing.equalTo(self.bottomContainerView!)
        }
        self.orderTimeView?.titleLabel?.text = "下单时间"
         
//        var orderNoView: JDCellInfoCellSubView?
//        var orderTimeView: JDCellInfoCellSubView?
//        var payTimeView: JDCellInfoCellSubView?
        
        self.payTimeView = JDCellInfoCellSubView()
        self.bottomContainerView?.addSubview(self.payTimeView!)
        self.payTimeView?.snp.makeConstraints { make in
            make.top.equalTo(self.orderTimeView!.snp.bottom)
            make.height.equalTo(32)
            make.leading.equalTo(self.bottomContainerView!)
            make.trailing.equalTo(self.bottomContainerView!)
            make.bottom.equalTo(self.bottomContainerView!).offset(-9)
        }
        self.payTimeView?.titleLabel?.text = "支付时间"
        
        
    }
    
    
    
    func getNetData() {
        var params = [String: Any]()
        params["orderId"] = self.orderId
        
        JDNetWorkRequest(.getOrderDetailInfo(params)) { responseStr in

            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                printLog("查询成功:\(responseStr)")
//                {"msg":"ok","data":{"goodsList":null,"payTime":"2025-04-06 13:30:49","tariff":null,"orderStatus":1,"province":null,"district":null,"shopName":null,"orderType":3,"city":null,"buyerName":null,"postal":null,"userMessage":null,"id":119,"orderNo":"JDCB1743783214748","deliveryNo":null,"freight":null,"receiverName":null,"acceptOrderTime":null,"mobile":null,"customerServicePhone":"0411-87979988","totalAmount":15000,"orderTime":"2025-04-05 00:13:35","buyerIdCardNumber":null,"address":null},"code":0}
                
                if let model = JDSimpleOrderDetailModel.deserialize(from: responseStr, designatedPath: "data") {
                    
                    self.detailModel = model
                    // TODO: 赋值 赋值
                    
                    self.topTitlelabel?.text = "尨看板"
                    
//                    var payTime: String?
//                    var orderStatus: String?
//                    var orderType: String?
//                    var orderNo: String?
//                    var orderTime: String?
                    
                    
                    
                    // 1：等付款，2：已付款待接单，3：接单待发货，
                    //        4：已发货待收，5：确认收货，6：订单取消,7：拒接订单
                    switch model.orderStatus {
                    case "1":
                        self.orderStatusLabel?.text = "5分钟后关闭"
                        self.orderStatusImageV?.isHidden = true
                    default:
                        self.orderStatusLabel?.text = "交易完成"
                        self.orderStatusImageV?.image = UIImage(named: "gotStatus")
                    }
                    
                    switch model.orderType ?? "-1" {
                    case "3":
                        self.setupNavigationTitle("尨看板详情")
                        self.topTitlelabel?.text = "尨看板"
                        self.contentLabel?.text = "尨看板发布一条信息"
                    case "4":
                        self.setupNavigationTitle("尨商圈详情")
                        self.topTitlelabel?.text = "尨商圈"
                        self.contentLabel?.text = "尨商圈发布一条咨询"
                    case "5":
                        self.setupNavigationTitle("提现详情")
                        self.topTitlelabel?.text = "用户提现"
                        self.contentLabel?.text = "用户进行一次提现"
                    default:
                        break
                    }
                    
                    self.orderNoView?.descriptionLabel?.text = model.orderNo
                    self.orderTimeView?.descriptionLabel?.text = model.orderTime
                    self.payTimeView?.descriptionLabel?.text = model.payTime
                    
//                    var allGoodsPrice = 0.0
//                    for goodsModel in model.goodsList ?? [JDOrderDetailGoodsModel]() {
//                        allGoodsPrice = allGoodsPrice + JSON(goodsModel.goodsPrice as Any).doubleValue * JSON(goodsModel.goodsCount as Any).doubleValue
//                    }
//                    self.totalPriceLabel?.text = String.init(format: "￥%.2f", (allGoodsPrice + JSON(model.tariff as Any).doubleValue + JSON(model.freight as Any).doubleValue)/1000.00)
//                    self.totalPriceLabel?.priceString(UIFont.systemFont(ofSize: 12, weight: .regular), UIFont.systemFont(ofSize: 20, weight: .semibold))
                    
                    
                    
                    let priceStr = String.init(format: "合计：￥%.2f", JSON(model.totalAmount as Any).doubleValue/1000.0)
                    self.totalPriceLabel?.attributedText = priceStr.attributed(firstStr: "合计：", first: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16, weight: .regular),NSAttributedString.Key.foregroundColor: color("#333333")], secondStr: "￥", second: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12, weight: .regular), NSAttributedString.Key.foregroundColor: color("#FA6161")], thirdStr: String(format: "%.2f", JSON(model.totalAmount as Any).doubleValue/1000.0), third: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 20, weight: .semibold),NSAttributedString.Key.foregroundColor: color("#FA6161")])
                    
                }
            }
//            self.mainTableView?.reloadData()
            
        } failure: { error in
            printLog("查询失败:\(error)")
            
        } error: { errorCode in
            printLog("查询错误:\(errorCode)")
            
        }

    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

// Action
extension JDSimpleOrderDetailViewController {
    @objc func cancelOrderAction(_ button: UIButton) {
        
        self.showConfirmView("是否确认取消订单？") { [weak self] in
            self?.cancelOrderRequest()
        }
        
    }
    
    func cancelOrderRequest() {
        var params = [String: Any]()
        params["orderId"] = self.orderId

        JDNetWorkRequest(.cancelOrder(params)) { responseStr in

            printLog("删除成功:\(responseStr)")

            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                self.backAction()
                self.simpleCallBack?()
            }

        } failure: { error in

        } error: { errorCode in

        }
    }
    
    
    @objc func continuePayAction() {
        
        var params = [String: Any]()
        params["orderNo"] = self.orderId
                    
        JDNetWorkRequest(.doOrderPay(params)) { responseStr in
            
            let paymentMethodView = JDPaymentMethodView()
            
            let priceStr = String.init(format: "￥%.2f", JSON(self.detailModel?.totalAmount as Any).doubleValue/1000.0)
            paymentMethodView.priceLabel?.text = priceStr
            paymentMethodView.priceLabel?.priceString(UIFont.systemFont(ofSize: 18, weight: .semibold), UIFont.systemFont(ofSize: 36, weight: .semibold))
            paymentMethodView.confirmButtonSelected = { [weak self] in
                print("看看这个接口吧:\(responseStr)")
                let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
                if commonModel?.code == "0" {
                    let alipayStr = JSON(commonModel?.data as Any).dictionaryValue["orderStr"]?.stringValue ?? ""
                    JDAlipayManager.pay(alipayStr)
                    paymentMethodView.removeFromSuperview()
                }
            }
            JDTools.getKeyWindows()?.rootViewController?.view.addSubview(paymentMethodView)

            
        } failure: { error in
            print("付款错误:\(error)")
            
        } error: { errorCode in
            print("付款异常code:\(errorCode)")
        }
        
//        self.showConfirmView("是否继续付款？") { [weak self] in
//
//        }
    }
    
}
